<?php
/**
 * Created by PhpStorm.
 * User: xiucai
 * Date: 2018/5/16
 * Time: 17:03
 */

namespace app\adminer\controller;

use think\Db;
use think\facade\Env;
use think\facade\Config;
use think\ueditor\Ueditor;
use PHPTool\SelectTree;

class News extends Adminbase
{
    public function index() {
        if(! $this->request->isAjax()) {
            return $this->fetch('newslist');
        } else {
            $categories = Db::name('news_category')->field('id, title')->select();
            $categoriesId = array_column($categories, 'id');
            $categoriesTitle = array_column($categories, 'title');
            $categoriesIdTitle = [];
            foreach ($categoriesId as $key => $cateId) {
                $categoriesIdTitle[$cateId] = $categoriesTitle[$key];
            }
            $count = Db::name('news')
                ->field('id,category,title,status,update_time')
                ->count();
            $newslist = Db::name('news')
                ->field('id,category,title,status,update_time')
                ->order('update_time', 'desc')
                ->select();
            foreach ($newslist as $key => $news) {
                if(in_array($news['category'], $categoriesId)) {
                    $newslist[$key]['category'] = $categoriesIdTitle[$news['category']];
                }
            }
            $data = [
                'count' => $count,
                'data'  => $newslist,
                'code'  => 0,
                'msg'   => 'success',
            ];
            echo json_encode($data);
            exit;
        }
    }

    public function add() {
        if($this->request->isGet()) {
            $categories = Db::name('news_category')
                ->field('id, pid parentid, title name')
                ->whereIn('status', [1,2])
                ->select();
            $st = new SelectTree($categories);
            $tree = $st->getArray(0,0);
            $this->assign('tree', $tree);
            return $this->fetch('newsadd');
        } else {
            $title = input('post.title');
            $category = input('post.category');
            $keywords = input('post.keywords');
            $description = input('post.description');
            $content = input('post.content');
            $add_time = date('Y-m-d H:i:s');

            if(empty($title)) {
                $this->resultData('$_222');
            }
            if(empty($category)) {
                $this->resultData('$_223');
            }
            if(empty($content)) {
                $this->resultData('$_224');
            }

            $insertData = [
                'title' => $title,
                'category' => $category,
                'keywords' => $keywords,
                'description' => $description,
                'content' => $content,
                'add_time' => $add_time,
                'update_time' => $add_time,
            ];
            $res = Db::name('news')->insert($insertData);
            $res ? $this->resultData('$_0') : $this->resultData('$_101');
        }

    }

    public function edit() {
        if($this->request->isGet()) {
            $id = input('get.id');
            $news = Db::name('news')->where(['id'=>$id])->find();
            $categories = Db::name('news_category')
                ->field('id, pid parentid, title name')
                ->select();
            $st = new SelectTree($categories);
            $tree = $st->getArray(0,0);

            $this->assign('tree', $tree);
            $this->assign('news', $news);
            return $this->fetch('newsedit');
        } else {
            $id = input('post.id');
            if(empty($id)) {
                $this->resultData('$_225');
            }

            $title = input('post.title');
            $category = input('post.category');
            $keywords = input('post.keywords');
            $description = input('post.description');
            $content = input('post.content');
            $add_time = date('Y-m-d H:i:s');

            if(empty($title)) {
                $this->resultData('$_222');
            }
            if(empty($category)) {
                $this->resultData('$_223');
            }
            if(empty($content)) {
                $this->resultData('$_224');
            }

            $updateData = [
                'title' => $title,
                'category' => $category,
                'keywords' => $keywords,
                'description' => $description,
                'content' => $content,
                'update_time' => $add_time,
            ];
            try{
                Db::name('news')->where(['id'=>$id])->update($updateData);
                return $this->resultData('$_0');
            } catch (\Exception $e) {
                return $this->resultData('$_101');
            }
        }
    }

    public function delete() {
        $id = input('post.id');
        if(empty($id)) {
            $this->resultData('$_220');
        }
        try {
            Db::name('news')->where(['id'=>$id])->update(['status'=>0]);
            $this->resultData('$_0');
        } catch (\Exception $e) {
            $this->resultData('$_101');
        }
    }

    public function upload() {
        $uploadPath = 'uploads/ueditor/image/';//上传地址
        $filepath = Env::get('root_path') . 'public/' . $uploadPath; // 文件全路径
        if(!file_exists($filepath)) {
            mkdir($filepath, 0755, true);
        }
        $file = request()->file('file');
        $info = $file->validate(Config::get('fileUpload'))->move($filepath);
        if($info){
            $data = [
                'code'  => 0,
                'data'  => [
                    'src'   => '/' . $uploadPath . $info->getSaveName(),
                    'title' => $info->getFilename(),
                ],
            ];
            exit(json_encode($data));
        } else {
            $data = [
                'code'  => 104,
                'msg'  => '文件上传失败',
            ];
            exit(json_encode($data));
        }
    }
    public function ueditor() {
        $data = new Ueditor();
        echo $data->output();
    }
}